package cn.lyjuan.aliyun.mq.conf.java.dynamic.producer;

import cn.lyjuan.aliyun.mq.conf.java.conf.MQAuthCst;
import cn.lyjuan.aliyun.mq.conf.java.dynamic.ADynamicBean;
import cn.lyjuan.aliyun.mq.conf.java.dynamic.MQUserCstDynamicImpl;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;

/**
 * Created by chad on 2016/10/11.
 */
public class MQProducerDynamicImpl extends ADynamicBean
{
    public static final String NAME_SUFFIX = "Producer";

    private Class<? extends cn.lyjuan.aliyun.mq.conf.java.conf.producer.AMQProducer> producerClass;

    public MQProducerDynamicImpl(String baseName, Class<? extends cn.lyjuan.aliyun.mq.conf.java.conf.producer.AMQProducer> producerClass)
    {
        super(baseName, NAME_SUFFIX);
        this.producerClass = producerClass;
    }

    @Override
    public void register(DefaultListableBeanFactory beanFactory)
    {
        if (isContainsBean(beanFactory)) return;

        // 将属性加载到BeanDefinition中
        BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(producerClass);
        builder.getBeanDefinition().setAttribute("id", this.getQuiteBeanName());
        builder.setInitMethodName("start");
        builder.setDestroyMethodName("shutdown");
        builder.setLazyInit(false);// 启动则加载
        // 改用setter方法
        builder.addPropertyReference("mQAuthCst", MQAuthCst.QUITE_BEAN_NAME);
        builder.addPropertyReference("mQUserCst", this.getQuiteBeanName(MQUserCstDynamicImpl.NAME_SUFFIX));
//        builder.addConstructorArgReference(MQAuthCst.QUITE_BEAN_NAME);
//        builder.addConstructorArgReference(this.getQuiteBeanName(MQUserCstDynamicImpl.NAME_SUFFIX));

        // 将Bean注册到SpringBeanFactory中
        beanFactory.registerBeanDefinition(this.getQuiteBeanName(), builder.getBeanDefinition());
    }
}
